/*
 * 文  件  名：MBeanExportManager.java
 * 版         权：Copyright©2013-2016 FuRongBao All Rights Reserved
 * 描         述：
 * 修  改  人：mq.zhang
 * 修改时间：2016年9月28日
 */
package com.mqzhang.common.jmx;

import java.lang.management.ManagementFactory;
import java.util.HashSet;
import java.util.Set;

import javax.management.MBeanServer;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;
import org.weakref.jmx.MBeanExporter;

import com.google.inject.name.Names;
import static org.weakref.jmx.ObjectNames.generatedNameOf;

/**
 * @author mq.zhang
 * @version V1.0 2016年9月28日
 */
@Service
public class MBeanExportManager implements BeanPostProcessor, DisposableBean {
    private static MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    private static MBeanExporter exporter = new MBeanExporter(server);
    private static Set<String> mBeanSet = new HashSet<String>();

    /**
     * {@inheritDoc}
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(JmxEbean.class)) {
            String objectName = generatedNameOf(bean.getClass(), Names.named(beanName));

            exporter.export(objectName, bean);
            mBeanSet.add(objectName);
        }

        return bean;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void destroy() throws Exception {
        for (String objectName : mBeanSet) {
            exporter.unexport(objectName);
        }
    }

}
